package com.xiaoming.e3mall.order.service.impl;

import com.xiaoming.e3mall.common.jedis.JedisClient;
import com.xiaoming.e3mall.common.utils.E3Result;
import com.xiaoming.e3mall.mapper.TbOrderItemMapper;
import com.xiaoming.e3mall.mapper.TbOrderMapper;
import com.xiaoming.e3mall.mapper.TbOrderShippingMapper;
import com.xiaoming.e3mall.order.pojo.OrderInfo;
import com.xiaoming.e3mall.order.service.OrderService;
import com.xiaoming.e3mall.pojo.TbOrderItem;
import com.xiaoming.e3mall.pojo.TbOrderShipping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 订单服务
 */
@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private JedisClient jedisClient;
    @Value("${ORDER_ID_GEN_KEY}")
    private String ORDER_ID_GEN_KEY;
    @Value("${ORDER_ID_START}")
    private String ORDER_ID_START;
    @Value("${ORDER_ITEM_ID_GEN_KEY}")
    private String ORDER_ITEM_ID_GEN_KEY;
    //订单mapper
    @Autowired
    private TbOrderMapper orderMapper;
    //订单详情 mapper
    @Autowired
    private TbOrderItemMapper orderItemMapper;
    //订单物流mapper
    @Autowired
    private TbOrderShippingMapper orderShippingMapper;


    /**
     * 创建订单:返回创建的订单号(供页面显示)
     */
    @Override
    public E3Result createOrder(OrderInfo orderInfo) {
        //接收controller传递过来的订单数据,补全信息,调用mapper持久化到数据库
        //生成订单号(使用redis的incr生成)
        if(!jedisClient.exists(ORDER_ID_GEN_KEY))
            jedisClient.set(ORDER_ID_GEN_KEY, ORDER_ID_START);
        String orderId = jedisClient.incr(ORDER_ID_GEN_KEY).toString();
        //补全属性
        orderInfo.setOrderId(orderId);
        //付款状态 //1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
        orderInfo.setStatus(1);
        //时间
        orderInfo.setCreateTime(new Date());
        orderInfo.setUpdateTime(new Date());
        //向订单表中插入数据
        orderMapper.insert(orderInfo);
        //向订单明细表中插入数据
        List<TbOrderItem> orderItemList = orderInfo.getOrderItems();
        for (TbOrderItem item : orderItemList) {
            //补全item的属性
            //设置item表中的id(采用redis中的自增长)
            String id = jedisClient.incr(ORDER_ITEM_ID_GEN_KEY).toString();
            //设置item表中的 order的主键值
            item.setId(id);
            item.setOrderId(orderId);
            orderItemMapper.insert(item);
        }

        //向订单物流表插入数据
        TbOrderShipping orderShipping = orderInfo.getOrderShipping();
        orderShipping.setOrderId(orderId);
        orderShipping.setCreated(new Date());
        orderShipping.setUpdated(new Date());
        orderShippingMapper.insert(orderShipping);
        //返回e3Result
        return E3Result.ok(orderId);
    }
}
